package com.tao.utilslib.log.logsave;

import com.tao.utilslib.data.Obj;
import com.tao.utilslib.file.FileUtil;
import com.tao.utilslib.log.logsave.task.ILogTask;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class BaseLogSaveer implements ILogSeaveer {
    private ExecutorService executorService;
    String path;
    long maxlog;

    public BaseLogSaveer(String path, long maxlog) {
        this.path = path;
        this.maxlog = maxlog;
        init();
    }

    public BaseLogSaveer(String path) {
        this(path, 1024 * 1024);
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setMaxlog(long maxlog) {
        this.maxlog = maxlog;
    }

    private void init() {
        release();
        executorService = Executors.newSingleThreadExecutor();
        try {
            FileUtil.ifNotExisCreateFiles(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void release() {
        if (Obj.notNULL(executorService)) executorService.shutdownNow();
        executorService = null;
    }

    public void log(String log) {
        try {
            FileUtil.ifNotExisCreateFiles(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.execute(getLogTask(log));
    }

    public abstract ILogTask getLogTask(String log);

    @Override
    public void clear() {
        FileWriter buffwr = null;
        try {
            buffwr = new FileWriter(new File(path));
            buffwr.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (Obj.notNULL(buffwr))
                    buffwr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
